<template>
	<uni-popup ref="popup" type="dialog">
		<view class="popup-container">
			<view class="popup-header">
				<text class="title">查看分组</text>
				<view class="header-actions">
					<uni-icons type="close" size="24" @click="close" />
				</view>
			</view>

			<view class="action-bar" v-if="mode === 'view'">
				<button class="action-btn" @click="handleCreate">新建</button>
				<button class="action-btn" @click="enterMergeMode">合并</button>
				<button class="action-btn" @click="enterEditMode">编辑</button>
			</view>
			<view class="action-bar" v-else-if="mode !== 'single-merge'">
				<button class="action-btn" @click="resetToView">返回</button>
			</view>

			<scroll-view class="group-list" scroll-y>
				<view class="group-item" v-for="(group, index) in groupList" :key="index">
					<checkbox-group v-if="mode !== 'view'" @change="toggleSelect(index)">
						<checkbox :checked="selectedGroups.includes(index)"
							:disabled="mode === 'edit' && group.name === '默认分组'" />
					</checkbox-group>
					<text class="group-name" @click="handleItemClick(index)">{{ group.name }}</text>
					<view class="action-area" v-if="mode === 'edit'">
						<uni-icons type="compose" size="20" @click="handleEdit(index)"
							:style="{color: group.name === '默认分组' ? '#ccc' : ''}" />
						<uni-icons type="trash" size="20" @click="handleDelete(index)"
							:style="{color: group.name === '默认分组' ? '#ccc' : ''}" />
					</view>
				</view>
			</scroll-view>

			<view class="footer-actions" v-if="mode !== 'view'">
				<button v-if="(mode === 'merge' && selectedGroups.length > 1) || 
                      (mode === 'single-merge' && selectedGroups.length === 1)" size="mini" class="confirm-btn"
					@click="handleMerge">
					{{ mode === 'single-merge' ? '确认合并' : `合并选中分组(${selectedGroups.length})` }}
				</button>
				<button v-if="mode === 'edit' && selectedGroups.length > 0" size="mini" class="confirm-btn delete"
					@click="batchDelete">
					批量删除({{ selectedGroups.length }})
				</button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	export default {
		name: "group-popup",
		emits: ["item-click", "single-merge", "merge", "create", "edit", "delete", "batch-delete"],
		data() {
			return {
				mode: 'view', // view/edit/merge/single-merge
				groupList: [],
				selectedGroups: []
			}
		},
		methods: {
			open(list) {
				this.groupList = list || []
				this.mode = 'view'
				this.selectedGroups = []
				this.$refs.popup.open()
			},
			close() {
				this.$refs.popup.close()
			},
			enterMergeMode() {
				this.mode = 'merge'
				this.selectedGroups = []
			},
			enterEditMode() {
				this.mode = 'edit'
				this.selectedGroups = []
			},
			// 添加返回查看模式的方法
			resetToView() {
				this.mode = 'view'
				this.selectedGroups = []
			},
			// 新增方法：打开单选合并模式
			openForSingleMerge(list) {
				this.groupList = list || []
				this.mode = 'single-merge'
				this.selectedGroups = []
				this.$refs.popup.open()
			},
			// 修改toggleSelect方法
			toggleSelect(index) {
				// 如果是编辑模式且是默认分组，则不允许选择
				if (this.mode === 'edit' && this.groupList[index].name === '默认分组') {
					return;
				}

				if (this.mode === 'single-merge') {
					// 单选合并模式下只能选一个
					this.selectedGroups = [index]
				} else {
					const idx = this.selectedGroups.indexOf(index)
					if (idx > -1) {
						this.selectedGroups.splice(idx, 1)
					} else {
						this.selectedGroups.push(index)
					}
				}
			},
			handleItemClick(index) {
				this.$emit('item-click', index)
				this.close()
			},
			handleMerge() {
				// 将默认分组移到最前面
				const sortedGroups = [...this.selectedGroups].sort((a, b) => {
					const aIsDefault = this.groupList[a].name === '默认分组';
					const bIsDefault = this.groupList[b].name === '默认分组';
					return bIsDefault - aIsDefault; // 默认分组排前面
				});

				if (this.mode === 'single-merge' && sortedGroups.length === 1) {
					const index = sortedGroups[0];
					const targetName = this.groupList[index].name;
					uni.showModal({
						title: '合并分组',
						content: `用户分享的数据即将合并到[${targetName}]分组,合并后原有相同的BOSS数据将被覆盖,是否确认合并`,
						success: (res) => {
							if (res.confirm) {
								this.$emit('single-merge', index);
								this.close();
							}
						}
					});
				} else {
					const defaultGroupIndex = sortedGroups.findIndex(
						index => this.groupList[index].name === '默认分组'
					);
					const targetIndex = defaultGroupIndex !== -1 ? defaultGroupIndex : 0;
					const targetName = this.groupList[sortedGroups[targetIndex]].name;

					const otherGroups = sortedGroups
						.filter((_, i) => i !== targetIndex)
						.map(index => this.groupList[index].name);

					uni.showModal({
						title: '合并分组',
						content: `所选[${otherGroups.join()}]分组即将合并到[${targetName}]分组,合并后原有相同的BOSS数据将被覆盖,是否确认合并`,
						success: (res) => {
							if (res.confirm) {
								this.$emit('merge', sortedGroups);
								this.close();
							}
						}
					});
				}
			},
			handleCreate() {
				uni.showModal({
					title: '新建分组',
					content: '',
					placeholderText: '请输入分组名称',
					editable: true,
					success: (res) => {
						if (res.confirm && res.content) {
							if (res.content === '默认分组') {
								uni.showToast({
									title: '不能使用"默认分组"作为名称',
									icon: 'none'
								});
								return;
							}
							const hasName = this.groupList.some(item =>
								item.name === res.content
							);
							if (hasName) {
								uni.showToast({
									title: `分组名称[${res.content}]已存在，请换个名称`,
									icon: 'none'
								});
								return;
							}
							this.$emit('create', res.content);
						}
					}
				});
			},
			handleEdit(index) {
				if (this.groupList[index].name === '默认分组') {
					uni.showToast({
						title: '不能修改"默认分组"',
						icon: 'none'
					});
					return;
				}
				uni.showModal({
					title: '编辑分组',
					content: this.groupList[index].name,
					placeholderText: '请输入分组名称',
					editable: true,
					success: (res) => {
						if (res.confirm && res.content) {
							if (res.content === '默认分组') {
								uni.showToast({
									title: '不能使用"默认分组"作为名称',
									icon: 'none'
								});
								return;
							}
							const hasName = this.groupList.some(item =>
								item.name === res.content
							);
							if (hasName) {
								uni.showToast({
									title: `[${res.content}]分组名称已存在，请换个名称`,
									icon: 'none'
								});
								return;
							}
							this.$emit('edit', {
								index,
								name: res.content
							});
						}
					}
				});
			},
			handleDelete(index) {
				if (this.groupList[index].name === '默认分组') {
					uni.showToast({
						title: '不能删除"默认分组"',
						icon: 'none'
					});
					return;
				}
				uni.showModal({
					title: '删除确认',
					content: `删除分组将会清空分组里面的所有数据，确定要删除[${this.groupList[index].name}]分组吗？`,
					success: (res) => {
						if (res.confirm) {
							this.$emit('delete', index);
						}
					}
				});
			},
			batchDelete() {
				const list = this.selectedGroups.map((index) => this.groupList[index].name)
				uni.showModal({
					title: '删除确认',
					content: `删除分组将会清空分组里面的所有数据，确定要删除[${list.join()}]分组吗？`,
					success: (res) => {
						if (res.confirm) {
							this.$emit('batch-delete', this.selectedGroups);
						}
					}
				});
			}
		}
	}
</script>

<style scoped>
	.popup-container {
		background-color: #fff;
		border-radius: 8px;
		padding: 15px;
		width: 80vw;
		max-width: 600rpx;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		padding-bottom: 10px;
		border-bottom: 1px solid #f0f0f0;
	}

	.title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.action-bar {
		display: flex;
		gap: 10px;
		margin-bottom: 12px;
	}

	.group-list {
		max-height: 60vh;
		min-height: 200rpx;
	}

	.group-item {
		display: flex;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px solid #f5f5f5;
		justify-content: space-between;
		/* 新增：让内容两端对齐 */
	}

	.group-name {
		flex: 1;
		margin-left: 10px;
	}

	.action-area {
		display: flex;
		gap: 30px;
		/* 增大按钮间距 */
		margin-left: 20px;
		/* 增加与名称的间距 */
	}

	/* 新增复选框样式 */
	checkbox-group {
		margin-right: 10px;
		transform: scale(0.7);
	}

	/* 调整底部按钮样式 */
	.footer-actions {
		margin-top: 15px;
		padding-top: 10px;
		border-top: 1px solid #f0f0f0;
	}

	.action-btn {
		flex: 1;
		background-color: #f8f8f8;
		color: #333;
		border-radius: 6px;
		font-size: 14px;
		height: 36px;
		line-height: 36px;
		transition: all 0.2s;
	}

	.action-btn:nth-child(1) {
		/* 新建按钮 */
		background-color: #4CAF50;
		color: white;
	}

	.action-btn:nth-child(2) {
		/* 合并按钮 */
		background-color: #2196F3;
		color: white;
	}

	.action-btn:nth-child(3) {
		/* 编辑按钮 */
		background-color: #FF9800;
		color: white;
	}

	.action-btn:active {
		opacity: 0.8;
		transform: scale(0.98);
	}

	.confirm-btn {
		width: 100%;
		padding: 0;
		background-color: #007AFF;
		color: white;
		border-radius: 6px;
		font-size: 14px;
		height: 36px;
		line-height: 36px;
	}

	.confirm-btn.delete {
		background-color: #FF2D2D;
		box-shadow: 0 1rpx 5px rgba(255, 45, 45, 0.3);
	}

	.confirm-btn:active {
		opacity: 0.9;
		transform: translateY(1px);
	}

	.popup-header .header-actions {
		/* 移除新建按钮后的调整 */
		gap: 0;
	}
</style>